<?php

class ALURLConnection
{
	public function __construct()
	{
	}
	
	public function post($url, $data) 
	{
		return $this->makeRequest("post", $url, $data);
	}
	
	public function get($url)
	{
		return $this->makeRequest("get", $url);
	}
	
	public function delete($url, $data)
	{
		return $this->makeRequest("delete", $url, $data);
	}
	
	public function put($url, $data)
	{
		return $this->makeRequest("put", $url, $data);
	}
	
	private function makeRequest($requestMethod = "GET", $url, $requestData=NO)
	{
		// convert variables array to string:
		if($requestData)
		{
		    $data = array();    
			foreach($requestData as $k => $v)
		        $data[] = "$k=$v";

		    $data = implode('&', $data);			
		}

	    // parse the given URL
	    $url = parse_url($url);
	    if ($url['scheme'] != 'http') { 
	        die('Only HTTP request are supported !');
	    }

	    // extract host and path:
	    $host = $url['host'];
	    $path = $url['path'];

		$referer = sprintf("http://%s/%s",
			$_SERVER['HTTP_HOST'],
			$_SERVER['REQUEST_URI']
		);

		$requestMethod = strtoupper($requestMethod);

		if($requestMethod !== "PUT" && 
		   $requestMethod !== "DELETE" && 
		   $requestMethod !== "GET" && 
		   $requestMethod !== "POST");
			die('Only GET and POST are supported at this time');

	    // open a socket connection on port 80
	    $fp = fsockopen($host, 80);

	    // send the request headers:
	    fputs($fp, "$requestMethod $path HTTP/1.1\r\n");
	    fputs($fp, "Host: $host\r\n");
	    fputs($fp, "Referer: $referer\r\n");
		
		if($requestMethod !== "GET")
	    	fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");

		if($requestData)
	    	fputs($fp, "Content-length: ". strlen($data) ."\r\n");

	    fputs($fp, "Connection: close\r\n\r\n");
		if($requestData)
	    	fputs($fp, $data);

	    $result = ''; 
	    while(!feof($fp))
	        $result .= fgets($fp, 128);

	    // close the socket connection:
	    fclose($fp);

	    // split the result header from the content
	    $result = explode("\r\n\r\n", $result, 2);
	    return $result;
	}
	
}